package org.jseda.thread;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * ThreadManager provides basic functionality for managing a collection of threads.
 * 
 * @author "John McNair" <john@mcnair.org>
 */
public class ThreadManager
{
	private static Logger logger = Logger.getLogger(ThreadManager.class);

	private Map<ManagedThread, Thread> threads = new HashMap<ManagedThread, Thread>();
	private long maxJoinTime = 120000L;

	/**
	 * @see ThreadManager.launch(ManagedThread managedThread).
	 */
	public void launch(ManagedThread managedThread)
	{
		Thread thread = new Thread(managedThread);
		thread.start();
		threads.put(managedThread, thread);
	}

	public void cancelAll()
	{
		for (ManagedThread managedThread : threads.keySet())
			managedThread.cancel();

		for (Thread thread : threads.values())
		{
			try
			{
				thread.join(maxJoinTime);
			}
			catch (InterruptedException ex)
			{
				logger.warn("Caught InterruptedException while joining threads");
			}
		}
	}
}
